package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Storage;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.service.WxStorageUploadService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author:tanxin Desc:
 * @date:2020/7/1 16:26
 */
@Service
public class WxStorageUploadServiceImpl implements WxStorageUploadService {


    @SneakyThrows
    @Override
    public BaseRespVO fileUpload(MultipartFile file, HttpServletRequest request, String uploadPath) {
        //原文件名
        String fileName = file.getOriginalFilename();
        //获取后缀名
        String endName = fileName.substring(fileName.lastIndexOf("."));
        //格式化时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间戳
        String timeStamp = simpleDateFormat.format(new Date());
        //文件名拼接
        String newName = "pic" + timeStamp + endName;
        //用一个文件来接收
        File dest = new File(uploadPath, newName);
        //检测路径是否存在
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String localAddr = request.getLocalAddr();
        if ("0:0:0:0:0:0:0:1".equals(localAddr) || "127.0.0.1".equals(localAddr)) {
            localAddr = "localhost";
        }
        String port = String.valueOf(request.getServerPort());

        uploadPath = "http://" + localAddr +":"+ port + "/" + newName;
        Storage storage = new Storage();
        storage.setUrl(uploadPath);
        return BaseRespVO.ok(storage);
    }
}
